import socket
import os.path
import io
import subprocess, datetime, time
filename = "index.html"
versionString = "<center>iix 0.2.5</center>"
mimeType = "text/html"

#yeah fuck you, this is just default header shit so it'll send a full header.

headerText = "HTTP/1.1 200 OK\nDate:"+str(time.time())+"\nServer: " + versionString +"\nLast-Modified: Wed, 08 Jan 2003 23:01:55 GMT\nEtag: \"3f80f-1b6-3e1cb03b\"\nAccept-Ranges: bytes\nConnection: close\nContent-Type: "+mimeType+"; charset=UTF-8\n\n"
Socket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
Socket.bind ( ( '', 8080 ) ) #because port 80 is only bindable by root
Socket.listen ( 1 )

class Handler:
	def handle(self):
		channel, details = Socket.accept()
		print 'We have opened a connection with', details
		data = channel.recv ( 100 )
		data = data.split()
		print data[1]
		filename = os.path.abspath("."+data[1])
		if filename == os.path.abspath("./"):
			filename = "index.html"
		if(filename.endswith("jpeg") or filename.endswith("jpg")):
			mimeType="image/jpeg"
		elif(filename.endswith("html") or filename.endswith("ixh") or filename.endswith("ixs")or filename.endswith("php")):
			mimeType="text/html"            
		else:
			mimeType="application/octet-stream"
			print mimeType
		print filename
		if os.path.exists(filename):
			if(mimeType=="text/html"):
				infile = open(filename,"r")
				content = infile.read()
				p = subprocess.Popen("php -f" + filename, shell=True, stdout=subprocess.PIPE)
				result = p.communicate()[0]
				print result
				content = result
				if content.find("!python") != -1:
					try:                
						p = subprocess.Popen("python " + filename, shell=True, stdout=subprocess.PIPE)
						result = p.communicate()[0]
						content = result
					except SyntaxError:
						content = "<html><center><br><h1>503</h1><br><h2>Internal Server Error</h2></center><br>"
				channel.send (headerText+content+"<br>"+versionString)
			elif(mimeType!="application/octet-stream"):
				test = os.path.getsize(filename)/(200*1024) + 1
				if test <= 0:
					test = 1
				print str(test) + " packets"
				for i in range(test):
					channel.send(io.FileIO(filename, "r").readall())
			else:
				channel.send(io.FileIO(filename, "r").readall())
				channel.close()
		else:
			channel.send("<html><br><h1>404</h1><br><h2>File not found</h2><br>"+versionString+"</html>")
			channel.close()

handler = Handler()
while True: 
	handler.handle()
